package cn.edu.scau.cmi.ema.controller;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiHibernateProxyUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

@Controller("EventController")
public class EventController extends CmiEmaController {

	@RequestMapping("/listEvents")
	public ModelAndView listEvents(HttpServletRequest request, @ModelAttribute CmiPagination pagination) {
		ModelAndView mav = new ModelAndView();

		pagination = eventPaginationService.updatePagination(request, pagination);
		Set<Event> events = eventPaginationService.getPaginationEvents(pagination);

		mav.addObject("events", events);
		mav.addObject("entityName", "event");
		mav.addObject("pagination", pagination);
		mav.setViewName("event/listEvents");
		return mav;
	}

	public String listEvents() {
		return "redirect:/listEvents";
	}

	//	进入，获取分页的引用属性，更新引用属性分页采用Ajax.
	@RequestMapping("/viewEvent")
	public ModelAndView viewEvent(@RequestParam Integer eventId, HttpServletRequest request, CmiPagination pagination) throws Throwable, SecurityException {
		ModelAndView mav = new ModelAndView();

//		(1) 获取事件
		Event event = eventDAO.findEventByPrimaryKey(eventId);

//		(2) 获取属性分页对象

		Map<String, CmiPagination> referenceCmiPaginationMap = eventPaginationService.getReferencePaginationMap(event);

		pagination = eventPaginationService.updatePagination(request, pagination);

//		获取事件分页了的属性对象
		Event referencePaginationEvent = eventPaginationService.getReferencePaginationEntity(event, pagination );

		mav.addObject("referenceCmiPaginationMap", referenceCmiPaginationMap);//分页对象
		mav.addObject("event", referencePaginationEvent);
		mav.addObject("entityName", "event");

//		mav.addObject("pagination", pagination);
		mav.setViewName("event/viewEvent");
		return mav;
	}


	@RequestMapping(value = "/confirmDeleteEvents")
	public ModelAndView confirmDeleteEvents(
			@RequestParam(value = "deleteEventsIds", required = true) Set<Integer> deleteEventsIds) {
		ModelAndView mav = new ModelAndView();

		Set<Event> deleteEvents = eventDAO.findEventsByIds(deleteEventsIds);
		Set<Event> referencedEvents = eventService.loadReferenceEvents(deleteEvents);
		boolean hasReferenced;
		if (referencedEvents.size() == 0) {
			mav.addObject("deleteEntitys", deleteEvents);
			hasReferenced = false;
		} else {
			deleteEvents.removeAll(referencedEvents);
			mav.addObject("referencedEntitys", referencedEvents);
			mav.addObject("deleteEntitys", deleteEvents);
			hasReferenced = true;
		}
		mav.addObject("entityName", "Event");
		mav.addObject("hasReferenced", hasReferenced);
		mav.setViewName("forward:/listEvents");
		return mav;
	}

	@RequestMapping("/deleteEvent")
	public String deleteEvent(@RequestParam Integer eventId) {
		Event event = eventDAO.findEventByPrimaryKey(eventId);
		eventService.deleteEvent(event);
		return "forward:/listEvents";
	}

	@RequestMapping("/confirmDeleteEvent")
	public ModelAndView confirmDeleteEvent(@RequestParam Integer eventId) {

		ModelAndView mav = new ModelAndView();

		mav.addObject("event", eventDAO.findEventByPrimaryKey(eventId));

		mav.setViewName("event/deleteEvent");

		return mav;
	}

	@RequestMapping("/deleteEvents")
	public String deleteEvents(@RequestParam(value = "deleteEventsId", required = true) Set<Integer> deleteEventsId) {
		eventService.deleteEvents(deleteEventsId);
		return "forward:/listEvents";
	}

	@RequestMapping("/editEvent")
	public ModelAndView editEvent(@RequestParam Integer eventId) {

		ModelAndView mav = new ModelAndView();

		Event event = eventDAO.findEventByPrimaryKey(eventId);
		// 将需要编辑的对象加到mav对象中
		mav.addObject("event", event);

		// 把所有的引用event对象都添加到mav对象，供前台页面选择
		mav.addAllObjects(eventService.loadEventObjectReferencedSet(event));

		// 将编辑页面event添加到mav中
		mav.setViewName("event/editEvent");
		return mav;
	}

	@RequestMapping("/newEvent")
	public ModelAndView newEvent() {
		ModelAndView mav = new ModelAndView();
		Event event = new Event();

		mav.addObject("event", event);

		// 把所有的引用event对象都添加到mav对象，供前台页面选择
		mav.addAllObjects(eventService.loadEventObjectReferencedSet(event));

		mav.addObject("newFlag", true);
		mav.setViewName("event/editEvent");

		return mav;
	}

	@RequestMapping("/saveEvent")
	public ModelAndView saveEvent(@ModelAttribute Event event) {

		ModelAndView mav = new ModelAndView();

		Address sourceAddressTemp = event.getSourceAddress();
		Address sourceAddress = sourceAddressTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(addressDAO.findAddressById(sourceAddressTemp.getId()));
		Address discoveryAddressTemp = event.getDiscoveryAddress();
		Address discoveryAddress = discoveryAddressTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(addressDAO.findAddressById(discoveryAddressTemp.getId()));
		Subject subjectTemp = event.getSubject();
		Subject subject = subjectTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(subjectDAO.findSubjectById(subjectTemp.getId()));
		User auditorTemp = event.getAuditor();
		User auditor = auditorTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(userDAO.findUserById(auditorTemp.getId()));
		Url urlTemp = event.getUrl();
		Url url = urlTemp == null ? null : CmiHibernateProxyUtil.deproxy(urlDAO.findUrlById(urlTemp.getId()));
		User reportorTemp = event.getReportor();
		User reportor = reportorTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(userDAO.findUserById(reportorTemp.getId()));
		Event parentTemp = event.getParent();
		Event parent = parentTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(eventDAO.findEventById(parentTemp.getId()));
		Foodbatch foodbatchTemp = event.getFoodbatch();
		Foodbatch foodbatch = foodbatchTemp == null ? null
				: CmiHibernateProxyUtil.deproxy(foodbatchDAO.findFoodbatchById(foodbatchTemp.getId()));

		Event existingEvent = CmiHibernateProxyUtil
				.deproxy(eventDAO.findEventByPhysicalPrimaryKey(subject.getId(), foodbatch.getId()));

		event.setSourceAddress(sourceAddress);
		event.setDiscoveryAddress(discoveryAddress);
		event.setSubject(subject);
		event.setAuditor(auditor);
		event.setUrl(url);
		event.setReportor(reportor);
		event.setParent(parent);
		event.setFoodbatch(foodbatch);
		// 新建记录
		if (event.getId() == null) {
			if (event.equals(existingEvent)) {

				mav.addAllObjects(eventService.loadEventClassReferencedSet(event));
				// mav = editContinue(mav, event);
				mav.addObject("isInsertSuccess", "false");
				mav.setViewName("event/editEvent");
			} else {
				eventService.saveEvent(event);
				mav.setViewName("forward:/listEvents");
			}
		}
		// 编辑记录
		else {
			Event originEvent = CmiHibernateProxyUtil.deproxy(eventDAO.findEventByPrimaryKey(event.getId()));
			if (!event.equals(originEvent) && event.equals(existingEvent)) {
				mav.addAllObjects(eventService.loadEventClassReferencedSet(event));
				mav.addObject("isInsertSuccess", "false");
				mav.setViewName("event/editEvent");
			} else {
				eventService.saveEvent(event);
				mav.setViewName("forward:/listEvents");
			}
		}
		return mav;
	}

	@RequestMapping("/eventController/binary.action")
	public ModelAndView streamBinary(@ModelAttribute HttpServletRequest request,
			@ModelAttribute HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("streamedBinaryContentView");
		return mav;

	}

}
